/**
 *  @file SyncWrap.h
 */
#ifndef _SYNCWRAP_H_
#define _SYNCWRAP_H_

#include "../common/NoCopyAndNew.h"

namespace cppflib
{

namespace threading
{

/**
 *
 *  This class is a friendly wrapper to use the one of the sync object (e.g. SyncLock, Semaphore, ...)
 *  to lock and unlock within a scope.
 *
 *  For example, 
 *
 *  =======================================================
 *
 *  SyncLock myLock;
 *
 *  void MyFunction(void)
 *  {
 *     SyncWrap<SyncLock> wrap(&myLock);  // create a local variable of SyncWrap here
 *     
 *     ...
 *     ..
 *
 *     // do something meaningful here
 *
 *  }
 *
 *  =======================================================
 *
 *  When a local variable of SyncWrap is created, the 'Lock' function of SyncLock is called automatically.
 *  Also, when function exits or execution is jumping out of a scope ( a 'while' loop or 'for' loop), the 
 *  destructor of SyncWrap is called and in turn the 'Unlock' function of the wrapped SyncLock is called, too.
 *
 */
template <class T>
class SyncWrap : public NoCopyAndNew
{
private:
   T *pSyncObj;

private:
   SyncWrap() { }

public:
   explicit SyncWrap(T *pSyncObj)
   {
      if (pSyncObj) {
         pSyncObj->Lock();
         this->pSyncObj = pSyncObj;
      }
      else {
         this->pSyncObj = NULL;
      }
   }

   ~SyncWrap()
   {
      if (this->pSyncObj)
         this->pSyncObj->Unlock();
   } 

};

} // end of namespace threading


} // end of namespace cppflib



#endif
